/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.activities.image;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.async.ManageSharingTask;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.android.widgets.view.CrossableItem;
import com.phonebooksharing.dto.ReturnItem;
import com.phonebooksharing.dto.gallery.ImageGalleryItem;

@SuppressWarnings("unchecked")
public class ImageGallerySharingActivity extends ListActivity {
    private ImageGalleryListAdapter adapter;
    private View emptyView;
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        
        setContentView(R.layout.list_layout_with_empty);
        
        emptyView = findViewById(R.id.empty);
        ((TextView)emptyView.findViewById(android.R.id.text1)).setText("Your Image Gallery is empty\n" +
                                                        "You're not sharing any picture");
        
        final ListView lv = getListView();

        adapter = new ImageGalleryListAdapter(ImageGallerySharingActivity.this, lv);
        adapter.checkListener = checkListener;

        lv.addFooterView(adapter.loading, null, false);
        lv.setAdapter(adapter);
        
        new LoadDataTask(lv).execute();
    }
    
    protected ArrayList<CrossableItem> checkList = new ArrayList<CrossableItem>();
    protected View.OnClickListener checkListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            ImageView iv = (ImageView)v.findViewById(R.id.check);
            CrossableItem vh = (CrossableItem)v.getTag();
            
            if(!vh.isCrossed) {
                iv.setImageState(new int[] { android.R.attr.state_checked }, true);
                iv.setTag("1");
                checkList.add(vh);
                vh.isCrossed = true;
            } else {
                iv.setImageState(new int[] { }, true);
                iv.setTag("0");
                checkList.remove(vh);
                vh.isCrossed = false;
            }
            
            final int s = checkList.size();
            if(s == 1) {//display actions
                showActionPanel();
            } else if (s == 0) {//display actions
                hideActionPanel();
            }
        }
    };
    
    private View actionsPanel;
    private boolean shown;
    private void showActionPanel() {
        View v = actionsPanel;
        if (shown) return;
        if (v == null) {
//            v = ((View) getParent().getParent()).findViewById(R.id.dash_actions);
            v = ((ViewStub)findViewById(R.id.actionStub)).inflate();
        }
        v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in));
        v.setVisibility(View.VISIBLE);
        //setup button archive
        Button b1 = (Button)v.findViewById(android.R.id.button1);
        b1.setText(getButtonLabel());
        b1.setOnClickListener(getButtonListener());
        
        v.findViewById(android.R.id.button2).setVisibility(View.INVISIBLE);
        actionsPanel = v;
        shown = true;
    }
    
    protected OnClickListener getButtonListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new InternalManageTask(ImageGallerySharingActivity.this, checkList, "nsig").execute();
            }
        };
    }
    
    class InternalManageTask extends ManageSharingTask {
        public InternalManageTask(Context cx, ArrayList<CrossableItem> checkList, String sharingType) {
            super(cx, checkList, sharingType);
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
        
        @Override
        protected void onPostExecute(ReturnItem result) {
            super.onPostExecute(result);
            finish();
            Toast.makeText(cx, "Your request has been successfully processed!", Toast.LENGTH_LONG).show();
        }
    }
    
    protected String getButtonLabel() {
        return "Stop Sharing";
    }
    
    private void hideActionPanel() {
        actionsPanel.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out));
        actionsPanel.setVisibility(View.GONE);

        shown = false;
    }
    
    class LoadDataTask extends NetworkHandlerTask<Void, Void, Void> {
        ListView lv;
        
        LoadDataTask(ListView lv) {
            this.lv = lv;
        }
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                ArrayList<ImageGalleryItem> photos = (ArrayList<ImageGalleryItem>)doNetworkPost(getUrl(), Global.authItem);
                if(photos != null && photos.size() > 0) {
                    ArrayList<CrossableItem<ImageGalleryItem>> wrapper = new ArrayList<CrossableItem<ImageGalleryItem>>();
                    for(ImageGalleryItem ig : photos) {
                        ig.timesViewedString = "Viewed by " + ig.timesViewed + " people";
                        wrapper.add(new CrossableItem<ImageGalleryItem>(ig));
                    }
                    adapter.items = wrapper;
                } else {//empty it up
                    adapter.items = new ArrayList<CrossableItem<ImageGalleryItem>>();
                }
                publishProgress();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            lv.removeFooterView(adapter.loading);
            if(adapter.items.size() == 0) {
                lv.setEmptyView(emptyView);
            } else {
                adapter.notifyDataSetChanged();
            }
        }
    }
    
    protected String getUrl() {
        return String.format(Global.IMAGE_SERVLET_URL, "p" /*ac*/, "s" /*q*/, "" /*c*/, "" /*p*/, "" /*ps*/, "" /*mt*/, "" /*w*/, "" /*h*/);
    }
}
